package com.yjha.lzmarathonsys.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjha.lzmarathonsys.bean.TbImagesl;
import com.yjha.lzmarathonsys.bean.TbPersonClockin;
import com.yjha.lzmarathonsys.mapper.TbImageslMapper;
import com.yjha.lzmarathonsys.service.TbImageslService;
import com.yjha.lzmarathonsys.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("tbImageslService")
public class TbImageslServiceImpl extends ServiceImpl<TbImageslMapper, TbImagesl> implements TbImageslService {

	@Autowired
	private HttpServletRequest request;
	@Autowired
	private FileUploadUtil fileUploadUtil;
	@Autowired
	private TbPersonClockinServiceImpl tbPersonClockinService;
	// @Value()
	// private String path;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<TbImagesl> page = this.page(
				new Query<TbImagesl>().getPage(params),
				new QueryWrapper<TbImagesl>()
		);

		return new PageUtils(page);
	}

	@Override
	@PostMapping("/uploadImages")
	public R fileUpload(String id, MultipartFile[] files) throws IOException {
		List<String> uploadedUrls = new ArrayList<>();

		for (MultipartFile file : files) {
			// 类型校验
			String s;
			if ("docx".equalsIgnoreCase(FileUtil.getSuffix(file.getOriginalFilename()))) {
				s = fileUploadUtil.validateFile(file, "WD");
			} else {
				s = fileUploadUtil.validateFile(file, "TP");
			}

			if (s != null) {
				return R.error("文件校验失败：" + s);
			}

			// 构建路径
			String suffix = FileUtil.getSuffix(file.getOriginalFilename());
			String fileName = StrUtil.uuid().replaceAll("-", "") + "." + suffix;
			String uploadDir = fileUploadUtil.getWinOrLinuxUploadFilePath("tp");
			String fullPath = uploadDir + fileName;

			// 创建目录
			fileUploadUtil.createDirectory(uploadDir);

			// 保存文件
			file.transferTo(FileUtil.file(fullPath));

			// 构建 URL 返回
			String fileUrl = RequestUtils.getBasePath(request) + "upload/tp/" + fileName;
			uploadedUrls.add(fileUrl);
		}
		Map<String, Object> map = new HashMap<>();
		List list = new ArrayList();
		for (int i = 0; i < uploadedUrls.size(); i++) {
			TbImagesl tbImagesl = new TbImagesl();
			tbImagesl.setTbImage(uploadedUrls.get(i));
			this.save(tbImagesl);
			list.add(tbImagesl);
		}
		map.put("list", list);
		return R.ok().put("data", map);
	}

	@Override
	public void removeTbImageslByIds(List<Integer> ids) {
		for (int i = 0; i < ids.size(); i++) {
			QueryWrapper<TbImagesl> imageslQueryWrapper = new QueryWrapper<TbImagesl>().eq("tb_id", ids.get(i));
			TbImagesl tbImagesl = this.getOne(imageslQueryWrapper);
			QueryWrapper<TbPersonClockin> tbPersonClockinQueryWrapper = new QueryWrapper<TbPersonClockin>().like("tb_imageids", tbImagesl.getTbId());
			List<TbPersonClockin> tbPersonClockinList = tbPersonClockinService.list(tbPersonClockinQueryWrapper);
			if (tbPersonClockinList.size() == 0) {
				this.removeById(ids.get(i));
				String uploadDir = fileUploadUtil.getWinOrLinuxUploadFilePath("tp");
				// 创建 File 对象
				File file = new File(tbImagesl.getTbImage());

				// 获取文件名（不包含路径）
				String fileName = file.getName();
				// 替换为你实际的文件路径
				String filePath = uploadDir + fileName;
				try {
					File file1 = new File(filePath);
					if (file1.delete()) {
						System.out.println("文件已删除: " + file.getName());
					} else {
						System.out.println("删除失败，文件可能不存在或被占用。");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

}